use std::{path::PathBuf, time::Duration};

use redis::{
  Client, ConnectionAddr, ConnectionInfo, ConnectionLike, RedisConnectionInfo, RedisResult,
};

pub fn redis_demo() -> RedisResult<()> {
  let is_single = false;
  if is_single {
    redis_single_demo()

    // let client = redis::Client::open("redis://192.168.110.26:6201/")?;
    // let mut conn = client.get_connection()?;
    // assert_eq!(true, conn.check_connection());
    // Ok(())
  } else {
    redis_cluster_demo()
  }
}

fn redis_single_demo() -> RedisResult<()> {
  let client = Client::open(get_connect_info(0))?;
  let mut conn = client.get_connection()?;

  /* do something here */
  conn.set_read_timeout(Some(Duration::from_millis(500)))?;
  conn.set_write_timeout(Some(Duration::from_millis(500)))?;
  // ConnectionLike::check_connection(&mut conn);

  assert_eq!(true, conn.check_connection());

  Ok(())
}

fn redis_cluster_demo() -> RedisResult<()> {
  use redis::cluster::ClusterClient;

  let nodes = vec![get_connect_info(0), get_connect_info(1)];
  let client = ClusterClient::open(nodes).unwrap();
  let mut conn = client.get_connection()?;
  assert_eq!(true, conn.check_connection());

  Ok(())
}

fn get_connect_info(index: i8) -> ConnectionInfo {
  // "192.168.110.26:6201,192.168.110.26:6202"
  let mut host = String::from("localhost");
  let mut port = 0;
  if index == 0 {
    host = String::from("192.168.110.26");
    port = 6201;
  } else if index == 1 {
    host = String::from("192.168.110.26");
    port = 6202;
  }
  let con_addr = ConnectionAddr::Tcp(host, port);
  // let con_addr = ConnectionAddr::Unix(PathBuf::from("192.168.110.26:6201"));
  let con_info = RedisConnectionInfo {
    db: 0,
    username: None,
    password: None,
  };
  return ConnectionInfo {
    addr: con_addr,
    redis: con_info,
  };
}
